package com.example.aiquestions.controller;

import com.example.aiquestions.entity.GraphData;
import com.example.aiquestions.entity.GraphRequest;
import com.example.aiquestions.entity.questionType;
import com.example.aiquestions.factory.AIServiceFactory;
import com.example.aiquestions.mapper.GraphMapper;
import com.example.aiquestions.mapper.SubjectMapper;
import com.example.aiquestions.model.common.ApiResponse;
import com.example.aiquestions.model.dto.ChatRequest;
import com.example.aiquestions.model.dto.ChatResponse;
import com.example.aiquestions.model.dto.GenerateQuestionRequest;
import com.example.aiquestions.model.dto.QuestionResponse;
import com.example.aiquestions.service.AIService;
import com.example.aiquestions.service.QuestionService;
import com.example.aiquestions.service.StreamResponseHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.RandomAccessReadBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;

@RestController
@CrossOrigin
@RequestMapping("/ai")
public class AIController {

    @Autowired
    private AIServiceFactory aiServiceFactory;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private GraphMapper graphMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private ObjectMapper objectMapper;

    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @PostMapping("/generate")
    public ApiResponse<List<Long>> generateQuestions(
            @RequestBody List<questionType> questionType,
            @RequestParam("message") String message,
            @RequestParam("easy") int easy,
            @RequestParam("medium") int medium,
            @RequestParam("hard") int hard,
            @RequestParam("provider") String provider,
            @RequestParam(value = "chatSession",required = false)String chatSession) {
        // 构建提示词
        StringBuilder prompt = new StringBuilder();
        prompt.append("请根据以下知识点:").append(message+"\n").append("，生成以下题目：\n");
        
        // 添加每种题型的要求
        for (questionType type : questionType) {
            if (type.getCount() > 0) {
                prompt.append("- ").append(type.getCount()).append("道")
                      .append(type.getLabel()).append("\n");
            }
        }        
        // 添加难度分布要求
        prompt.append("\n题目难度分布要求：\n")
              .append("- 简单题占").append(easy).append("%\n")
              .append("- 中等题占").append(medium).append("%\n")
              .append("- 困难题占").append(hard).append("%\n");             
        
        String userPrompt = prompt.toString();
        /**例子
         * 请根据以下知识点:java多线程
        ，生成以下题目：
        - 1道单选题
        - 5道多选题
        - 2道简答题

        题目难度分布要求：
        - 简单题占30%
        - 中等题占40%
        - 困难题占30%
         */
        try {
            // 获取指定的AI服务
            AIService aiService = aiServiceFactory.getService(provider);
            
            // 调用AI生成题目
            ChatResponse chatResponse = aiService.generateQuestion(userPrompt);
//            ChatResponse chatResponse = new ChatResponse();
            // 获取AI返回的内容
            String content = chatResponse.getChoices().get(0).getMessage().getContent();
            System.out.println("AI返回的原始内容：" + content);  // 添加日志
            
            // 清理Markdown格式标记和其他无关内容
            content = content.replaceAll("```json\\s*", "")  // 移除开始的```json
                           .replaceAll("```\\s*$", "")       // 移除结尾的```
                           .replaceAll("^\\s+|\\s+$", "");   // 移除首尾空白
            
            System.out.println("清理后的内容：" + content);  // 添加日志
            
            try {
                // 尝试解析JSON数组
                List<QuestionResponse.QuestionData> questions = objectMapper.readValue(
                    content,
                    objectMapper.getTypeFactory().constructCollectionType(
                        List.class,
                        QuestionResponse.QuestionData.class
                    )
                );
                
                // 保存题目到数据库
                List<Long> questionIds = questionService.saveQuestions(questions);
                return ApiResponse.success(questionIds);
                
            } catch (Exception e) {
                System.out.println("JSON解析错误：" + e.getMessage());  // 添加错误日志
                // 如果解析失败，尝试清理内容中的特殊字符后重试
                content = content.replaceAll("[\\x00-\\x1F\\x7F]", "")  // 移除控制字符
                                .replaceAll("`", "")                     // 移除反引号
                                .trim();                                // 移除首尾空白
                                
                List<QuestionResponse.QuestionData> questions = objectMapper.readValue(
                    content,
                    objectMapper.getTypeFactory().constructCollectionType(
                        List.class,
                        QuestionResponse.QuestionData.class
                    )
                );
                
                // 保存题目到数据库
                List<Long> questionIds = questionService.saveQuestions(questions);
                return ApiResponse.success(questionIds);
            }
        } catch (Exception e) {
            e.printStackTrace();  // 打印完整堆栈信息
            return ApiResponse.error(500, "生成题目失败：" + e.getMessage());
        }
    }

    @PostMapping("/generate/graph")
    public ApiResponse<List<GraphData>> generateGraphData(
            @RequestBody GraphRequest graphRequest,
            @RequestParam("provider") String provider) {
        
        try {
            // 获取指定的AI服务
            AIService aiService = aiServiceFactory.getService(provider);
            
            // 构建提示词 - 直接将用户传入的message作为输入
            String userPrompt = graphRequest.getMessage();
            
            // 调用AI服务生成知识图谱数据
            ChatResponse chatResponse = aiService.generateGraphData(userPrompt);
            
            // 获取AI返回的内容
            if (chatResponse == null || chatResponse.getChoices() == null || chatResponse.getChoices().isEmpty()) {
                return ApiResponse.error(500, "AI返回的内容为空");
            }
            
            String content = chatResponse.getChoices().get(0).getMessage().getContent();
            System.out.println("AI返回的原始内容：" + content);
            
            if (content == null || content.trim().isEmpty()) {
                return ApiResponse.error(500, "AI返回的内容为空");
            }
            
            // 清理Markdown格式标记和其他无关内容
            content = content.replaceAll("```json\\s*", "")  // 移除开始的```json
                           .replaceAll("```\\s*$", "")       // 移除结尾的```
                           .replaceAll("^\\s+|\\s+$", "");   // 移除首尾空白
            
            try {
                // 解析JSON数组
                List<GraphData> graphDataList = objectMapper.readValue(
                    content,
                    objectMapper.getTypeFactory().constructCollectionType(
                        List.class,
                        GraphData.class
                    )
                );
                String subjectName = subjectMapper.getSubjectById(graphRequest.getSubjectId()).getName();
                // 设置subjectId
                for (GraphData graphData : graphDataList) {
                    graphData.setSubjectId(graphRequest.getSubjectId());
                    graphData.setSubjectName(subjectName);
                }
                
                // 将生成的知识图谱数据保存到数据库
                if (graphDataList != null && !graphDataList.isEmpty()) {
                    int inserted = graphMapper.batchInsertGraphData(graphDataList);
                    System.out.println("成功插入 " + inserted + " 条知识图谱数据");
                }
                
                return ApiResponse.success(graphDataList);
                
            } catch (Exception e) {
                System.out.println("JSON解析错误：" + e.getMessage());
                e.printStackTrace();
                
                // 尝试修复JSON格式后重新解析
                try {
                    content = content.replaceAll("[\\x00-\\x1F\\x7F]", "")  // 移除控制字符
                                   .replaceAll("`", "")                     // 移除反引号
                                   .trim();                                // 移除首尾空白
                    
                    List<GraphData> graphDataList = objectMapper.readValue(
                        content,
                        objectMapper.getTypeFactory().constructCollectionType(
                            List.class,
                            GraphData.class
                        )
                    );
                    
                    // 设置subjectId
                    for (GraphData graphData : graphDataList) {
                        graphData.setSubjectId(graphRequest.getSubjectId());
                    }
                    
                    // 将生成的知识图谱数据保存到数据库
                    if (graphDataList != null && !graphDataList.isEmpty()) {
                        int inserted = graphMapper.batchInsertGraphData(graphDataList);
                        System.out.println("成功插入 " + inserted + " 条知识图谱数据");
                    }
                    
                    return ApiResponse.success(graphDataList);
                } catch (Exception ex) {
                    return ApiResponse.error(500, "解析知识图谱数据失败：" + ex.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500, "生成知识图谱数据失败：" + e.getMessage());
        }
    }

    @PostMapping("/chat")
    public ApiResponse<ChatResponse> chat(
            @RequestBody ChatRequest request,
            @RequestParam(defaultValue = "deepseek") String provider) {
        AIService aiService = aiServiceFactory.getService(provider);
        return ApiResponse.success(aiService.chat(request));
    }

    @PostMapping("/send")
    public ApiResponse<ChatResponse> sendMessage(
            @RequestParam String message,
            @RequestParam(defaultValue = "deepseek") String provider) {
        AIService aiService = aiServiceFactory.getService(provider);
        return ApiResponse.success(aiService.sendMessage(message));
    }

    @GetMapping("/provider")
    public ApiResponse<String> getProvider(
            @RequestParam(defaultValue = "deepseek") String provider) {
        AIService aiService = aiServiceFactory.getService(provider);
        return ApiResponse.success(aiService.getProvider());
    }

    /**
     * 上传文件支持 .txt、.doc、.docx、.pdf 格式文件
     * @param file
     * @return 返回文本
     */
    @PostMapping("/upload")
    public ApiResponse<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ApiResponse.error(500,"文件为空");
            }

            // 检查文件格式是否支持
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            if (fileExtension == null || !SUPPORTED_FORMATS.contains(fileExtension.toLowerCase())) {
                return ApiResponse.error(500,"不支持的文件格式，仅支持.txt、.doc、.docx、.pdf");
            }

            // 解析文件内容
            String text = parseFile(file, fileExtension);
            return ApiResponse.success(text);

        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error(500,"文件解析失败:" + e.getMessage());
        }
    }

    private static final Set<String> SUPPORTED_FORMATS = Set.of("txt", "doc", "docx", "pdf");
    private String getFileExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
            return null;
        }
        return filename.substring(lastDotIndex + 1);
    }

    private String parseFile(MultipartFile file, String fileExtension) throws Exception {
        String content = "";
        switch (fileExtension.toLowerCase()) {
            case "txt":
                content = parseTextFile(file);
                break;
            case "doc":
                content = parseWordFile(file, false);
                break;
            case "docx":
                content = parseWordFile(file, true);
                break;
            case "pdf":
                content = parsePdfFile(file);
                break;
            default:
                throw new IllegalArgumentException("不支持的文件格式");
        }
        return content;
    }

    private String parseTextFile(MultipartFile file) throws IOException {
        return new String(file.getBytes(), StandardCharsets.UTF_8);
    }

    private String parseWordFile(MultipartFile file, boolean isDocx) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            if (isDocx) {
                // 使用 Apache POI 解析 .docx 文件
                XWPFDocument document = new XWPFDocument(inputStream);
                XWPFWordExtractor extractor = new XWPFWordExtractor(document);
                return extractor.getText();
            } else {
                // 使用 Apache POI 解析 .doc 文件
                HWPFDocument document = new HWPFDocument(inputStream);
                WordExtractor extractor = new WordExtractor(document);
                return extractor.getText();
            }
        }
    }
    private String parsePdfFile(MultipartFile file) throws Exception {
        try (InputStream inputStream = file.getInputStream()) {
            // 使用 RandomAccessReadBuffer 将 InputStream 转换为 RandomAccessRead
            RandomAccessRead randomAccessRead = new RandomAccessReadBuffer(inputStream);

            // 使用 PDFBox 的 Loader 加载 PDF 文件
            PDDocument pdDocument = Loader.loadPDF(randomAccessRead);

            // 使用 PDFTextStripper 提取文本
            PDFTextStripper pdfStripper = new PDFTextStripper();
            return pdfStripper.getText(pdDocument);
        }
    }

    @PostMapping("/generate/stream")
    public SseEmitter generateQuestionsStream(
            @RequestBody GenerateQuestionRequest request,
            @RequestParam("provider") String provider,
            @RequestParam(value = "chatSession",required = false) String chatSession) {
        
        // 增加超时时间到15分钟
        SseEmitter emitter = new SseEmitter(900000L);
        
        // 添加完成和超时回调
        emitter.onCompletion(() -> {
            System.out.println("题目生成SSE连接已完成");
        });
        
        emitter.onTimeout(() -> {
            System.out.println("题目生成SSE连接超时");
            try {
                emitter.send(SseEmitter.event()
                    .name("error")
                    .data("生成题目超时，请重试或使用非流式API"));
                emitter.complete();
            } catch (IOException e) {
                // 忽略超时时的发送错误
            }
        });
        
        // 防止报错时，emitter无法关闭
        AtomicBoolean completed = new AtomicBoolean(false);
        
        executorService.execute(() -> {
            // 用于定时发送心跳
            ScheduledExecutorService heartbeatExecutor = null;
            
            try {
                // 构建提示词
                StringBuilder prompt = new StringBuilder();
                prompt.append("请根据以下知识点:").append(request.getMessage()+"\n").append("，生成以下题目：\n");
                
                // 添加每种题型的要求
                for (questionType type : request.getQuestionTypes()) {
                    if (type.getCount() > 0) {
                        prompt.append("- ").append(type.getCount()).append("道")
                              .append(type.getLabel()).append("\n");
                    }
                }        
                // 添加难度分布要求
                prompt.append("\n题目难度分布要求：\n")
                      .append("- 简单题占").append(request.getEasy()).append("%\n")
                      .append("- 中等题占").append(request.getMedium()).append("%\n")
                      .append("- 困难题占").append(request.getHard()).append("%\n");             
                
                String userPrompt = prompt.toString();
                
                // 获取指定的AI服务
                AIService aiService = aiServiceFactory.getService(provider);
                
                // 发送开始生成的消息
                emitter.send(SseEmitter.event()
                    .name("generating")
                    .data("开始生成题目..."));

                // 添加心跳消息，每20秒发送一次，防止连接超时
                heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
                ScheduledExecutorService finalHeartbeatExecutor = heartbeatExecutor;
                heartbeatExecutor.scheduleAtFixedRate(() -> {
                    try {
                        if (!completed.get()) {
                            emitter.send(SseEmitter.event()
                                .name("heartbeat")
                                .data("processing"));
                        }
                    } catch (Exception e) {
                        // 如果发送失败，忽略异常并尝试关闭定时器
                        try {
                            finalHeartbeatExecutor.shutdown();
                        } catch (Exception ignored) {}
                    }
                }, 10, 20, TimeUnit.SECONDS);

                // 创建流式回调处理器
                StreamResponseHandler streamHandler = new StreamResponseHandler() {
                    private final List<Long> allQuestionIds = new ArrayList<>();
                    private int processedQuestions = 0;
                    private final Object lock = new Object(); // 添加锁来保护共享资源
                    private final AtomicBoolean handlerCompleted = new AtomicBoolean(false);

                    @Override
                    public void onNext(String chunk) {
                        // 如果已经标记为完成，不再处理新数据
                        if (completed.get() || handlerCompleted.get()) {
                            System.out.println("SseEmitter已完成，停止处理新数据");
                            return;
                        }
                        
                        try {
                            // 如果是JSON数组格式，说明是完整的题目数据
                            if (chunk.trim().startsWith("[") && chunk.trim().endsWith("]")) {
                                try {
                                    // 解析题目数据
                                    List<QuestionResponse.QuestionData> questions = objectMapper.readValue(
                                        chunk,
                                        objectMapper.getTypeFactory().constructCollectionType(
                                            List.class,
                                            QuestionResponse.QuestionData.class
                                        )
                                    );
                                    
                                    if (questions != null && !questions.isEmpty()) {
                                        // 保存题目并发送进度
                                        for (QuestionResponse.QuestionData question : questions) {
                                            // 避免并发问题
                                            synchronized (lock) {
                                                // 再次检查是否已完成
                                                if (completed.get() || handlerCompleted.get()) {
                                                    return;
                                                }
                                                
                                                try {
                                                    // 保存单个题目
                                                    List<Long> ids = questionService.saveQuestions(List.of(question));
                                                    if (!ids.isEmpty()) {
                                                        Long questionId = ids.get(0);
                                                        allQuestionIds.add(questionId);
                                                        processedQuestions++;
                                                        
                                                        if (!completed.get() && !handlerCompleted.get()) {
                                                            try {
                                                                // 发送题目ID
                                                                emitter.send(SseEmitter.event()
                                                                    .name("questionId")
                                                                    .data(questionId));
                                                                
                                                                // 发送进度（这里我们假设总题目数是通过题型统计得到的）
                                                                int totalExpectedQuestions = request.getQuestionTypes().stream()
                                                                    .mapToInt(questionType::getCount)
                                                                    .sum();
                                                                
                                                                float progress = (processedQuestions * 100.0f) / totalExpectedQuestions;
                                                                progress = Math.min(progress, 100.0f); // 确保不超过100%
                                                                
                                                                emitter.send(SseEmitter.event()
                                                                    .name("progress")
                                                                    .data(String.format("%.1f", progress)));
                                                                
                                                                // 不要频繁发送完整题目列表，减少数据量
                                                                if (processedQuestions % 5 == 0 || processedQuestions == totalExpectedQuestions) {
                                                                    // 发送当前所有题目ID列表
                                                                    emitter.send(SseEmitter.event()
                                                                        .name("questions")
                                                                        .data(allQuestionIds));
                                                                }
                                                            } catch (IOException e) {
                                                                System.err.println("发送SSE事件失败，可能连接已关闭: " + e.getMessage());
                                                                handlerCompleted.set(true);
                                                                // 不抛出异常，让处理继续，只是不再发送事件
                                                            }
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    System.err.println("Error saving question: " + e.getMessage());
                                                    // 继续处理，不要因为一个题目保存失败就中断整个流程
                                                }
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    System.err.println("Error processing questions: " + e.getMessage());
                                    // 不抛出异常，继续处理后续数据
                                }
                            }
                        } catch (Exception e) {
                            System.err.println("处理流式数据异常: " + e.getMessage());
                            // 不抛出异常，继续处理后续数据
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        synchronized (lock) {
                            if (!handlerCompleted.get() && !completed.get()) {
                                try {
                                    System.err.println("生成题目错误: " + throwable.getMessage());
                                    throwable.printStackTrace();
                                    emitter.send(SseEmitter.event()
                                        .name("error")
                                        .data("生成题目失败：" + throwable.getMessage()));
                                    
                                    handlerCompleted.set(true);
                                    completed.set(true);
                                    emitter.complete();
                                } catch (IOException e) {
                                    // 忽略发送错误
                                    System.err.println("发送错误事件失败，连接可能已关闭: " + e.getMessage());
                                }
                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        synchronized (lock) {
                            if (!handlerCompleted.get() && !completed.get()) {
                                try {
                                    if (!allQuestionIds.isEmpty()) {
                                        // 发送所有题目ID
                                        emitter.send(SseEmitter.event()
                                            .name("questions")
                                            .data(allQuestionIds));
                                            
                                        emitter.send(SseEmitter.event()
                                            .name("complete")
                                            .data("题目生成完成，共生成 " + allQuestionIds.size() + " 道题目"));
                                    } else {
                                        emitter.send(SseEmitter.event()
                                            .name("error")
                                            .data("未能成功生成题目"));
                                    }
                                    
                                    handlerCompleted.set(true);
                                    completed.set(true);
                                    emitter.complete();
                                } catch (IOException e) {
                                    // 忽略发送错误
                                    System.err.println("发送完成事件失败，连接可能已关闭: " + e.getMessage());
                                }
                            }
                        }
                    }
                };
                
                try {
                    // 调用AI生成题目（使用流式接口）
                    aiService.generateQuestionStream(userPrompt, streamHandler);
                } catch (UnsupportedOperationException ex) {
                    // 处理不支持流式生成的情况
                    System.out.println("Provider " + provider + " 不支持流式生成题目，尝试使用普通方法");
                    ChatResponse response = aiService.generateQuestion(userPrompt);
                    String content = response.getChoices().get(0).getMessage().getContent();
                    streamHandler.onNext(content);
                    streamHandler.onComplete();
                }
                
            } catch (Exception e) {
                try {
                    System.err.println("生成题目过程异常: " + e.getMessage());
                    e.printStackTrace();
                    if (!completed.get()) {
                        emitter.send(SseEmitter.event()
                            .name("error")
                            .data("生成题目失败：" + e.getMessage()));
                            
                        completed.set(true);
                        emitter.complete();
                    }
                } catch (IOException ex) {
                    // 忽略二次异常
                } finally {
                    // 确保心跳定时器被关闭
                    if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
                        heartbeatExecutor.shutdown();
                    }
                }
            } finally {
                // 确保心跳定时器被关闭
                if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) {
                    heartbeatExecutor.shutdown();
                }
            }
        });
        
        return emitter;
    }

    @PostMapping("/generate/graph/stream")
    public SseEmitter generateGraphDataStream(
            @RequestBody GraphRequest graphRequest,
            @RequestParam("provider") String provider) {
        
        // 打印输入参数信息，帮助诊断
        System.out.println("接收到知识图谱生成请求，提供者: " + provider);
        System.out.println("输入内容长度: " + (graphRequest.getMessage() != null ? graphRequest.getMessage().length() : 0));
        System.out.println("学科ID: " + graphRequest.getSubjectId());
        
        // 创建SSE发射器，设置15分钟超时
        SseEmitter emitter = new SseEmitter(900000L);
        
        executorService.execute(() -> {
            try {
                // 获取AI服务
                AIService aiService = aiServiceFactory.getService(provider);
                if (aiService == null) {
                    emitter.send(SseEmitter.event()
                        .name("message")
                        .data("{\"name\":\"error\",\"data\":\"不支持的AI提供者: " + provider + "\"}"));
                    emitter.complete();
                    return;
                }
                
                // 获取学科名称
                String subjectName = subjectMapper.getSubjectById(graphRequest.getSubjectId()).getName();
                System.out.println("学科名称: " + subjectName);
                
                // 创建StreamResponseHandler处理流式响应
                StreamResponseHandler handler = new StreamResponseHandler() {
                    private final List<GraphData> allGraphData = Collections.synchronizedList(new ArrayList<>());
                    private final AtomicBoolean completed = new AtomicBoolean(false);
                    
                    @Override
                    public void onNext(String chunk) {
                        try {
                            System.out.println("收到AI返回的数据: " + chunk);
                            
                            // 解析JSON数组
                            JsonArray dataArray = JsonParser.parseString(chunk).getAsJsonArray();
                            int batchSize = dataArray.size();
                            System.out.println("解析到" + batchSize + "条知识点数据");
                            
                            if (batchSize > 0) {
                                List<GraphData> graphDataList = new ArrayList<>();
                                
                                // 遍历每个知识点，转换为GraphData对象
                                for (JsonElement element : dataArray) {
                                    JsonObject item = element.getAsJsonObject();
                                    
                                    GraphData graphData = new GraphData();
                                    graphData.setChapter(item.get("chapter").getAsInt());
                                    graphData.setNode(item.get("node").getAsInt());
                                    graphData.setKnowledge(item.get("knowledge").getAsString());
                                    graphData.setMastery(item.get("mastery").getAsString());
                                    graphData.setDifficulty(item.get("difficulty").getAsInt());
                                    
                                    // 设置学科ID和名称
                                    graphData.setSubjectId(graphRequest.getSubjectId());
                                    graphData.setSubjectName(subjectName);
                                    
                                    graphDataList.add(graphData);
                                    allGraphData.add(graphData);
                                }
                                
                                // 将数据保存到数据库
                                int insertedCount = graphMapper.batchInsertGraphData(graphDataList);
                                System.out.println("成功插入" + insertedCount + "条知识点到数据库");
                                
                                // 发送进度消息到前端
                                JsonObject progressEvent = new JsonObject();
                                progressEvent.addProperty("name", "progress");
                                progressEvent.addProperty("data", "已生成并保存" + allGraphData.size() + "条知识点数据");
                                
                                emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data(progressEvent.toString()));
                                
                                // 发送当前批次数据给前端
                                JsonObject dataEvent = new JsonObject();
                                dataEvent.addProperty("name", "data");
                                
                                // 将GraphData转换为JSON
                                String jsonData = objectMapper.writeValueAsString(graphDataList);
                                JsonElement jsonElement = JsonParser.parseString(jsonData);
                                dataEvent.add("data", jsonElement);
                                
                                emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data(dataEvent.toString()));
                            }
                        } catch (Exception e) {
                            System.err.println("处理数据块时出错: " + e.getMessage());
                            e.printStackTrace();
                            
                            try {
                                JsonObject errorEvent = new JsonObject();
                                errorEvent.addProperty("name", "warning");
                                errorEvent.addProperty("data", "处理部分数据出错: " + e.getMessage());
                                
                                emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data(errorEvent.toString()));
                            } catch (Exception ex) {
                                System.err.println("发送错误消息失败: " + ex.getMessage());
                            }
                        }
                    }
                    
                    @Override
                    public void onError(Throwable throwable) {
                        if (completed.compareAndSet(false, true)) {
                            System.err.println("处理过程中发生错误: " + throwable.getMessage());
                            throwable.printStackTrace();
                            
                            try {
                                JsonObject errorEvent = new JsonObject();
                                errorEvent.addProperty("name", "error");
                                errorEvent.addProperty("data", "生成知识图谱时出错: " + throwable.getMessage());
                                
                                emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data(errorEvent.toString()));
                                
                                // 如果已经生成了一些数据，则告知前端
                                if (!allGraphData.isEmpty()) {
                                    JsonObject completeEvent = new JsonObject();
                                    completeEvent.addProperty("name", "complete");
                                    completeEvent.addProperty("data", "部分完成，已生成" + allGraphData.size() + "条知识点");
                                    
                                    emitter.send(SseEmitter.event()
                                        .name("message")
                                        .data(completeEvent.toString()));
                                    
                                    emitter.complete();
                                } else {
                                    emitter.completeWithError(throwable);
                                }
                            } catch (IOException e) {
                                System.err.println("发送错误消息失败: " + e.getMessage());
                                emitter.completeWithError(throwable);
                            }
                        }
                    }
                    
                    @Override
                    public void onComplete() {
                        if (completed.compareAndSet(false, true)) {
                            try {
                                int totalPoints = allGraphData.size();
                                System.out.println("知识图谱生成完成，共" + totalPoints + "条知识点");
                                
                                JsonObject completeEvent = new JsonObject();
                                completeEvent.addProperty("name", "complete");
                                
                                if (totalPoints > 0) {
                                    completeEvent.addProperty("data", "知识图谱生成完成，共" + totalPoints + "条知识点");
                                    
                                    emitter.send(SseEmitter.event()
                                        .name("message")
                                        .data(completeEvent.toString()));
                                    
                                    emitter.complete();
                                } else {
                                    completeEvent.addProperty("data", "未能生成任何知识点，请检查输入内容");
                                    
                                    emitter.send(SseEmitter.event()
                                        .name("message")
                                        .data(completeEvent.toString()));
                                    
                                    emitter.complete();
                                }
                            } catch (IOException e) {
                                System.err.println("发送完成消息失败: " + e.getMessage());
                                e.printStackTrace();
                                try {
                                    emitter.completeWithError(e);
                                } catch (Exception ex) {
                                    System.err.println("完成处理出错: " + ex.getMessage());
                                }
                            }
                        }
                    }
                };
                
                // 发送开始消息
                JsonObject startEvent = new JsonObject();
                startEvent.addProperty("name", "progress");
                startEvent.addProperty("data", "开始生成知识图谱...");
                
                emitter.send(SseEmitter.event()
                    .name("message")
                    .data(startEvent.toString()));
                
                // 调用AI服务生成知识图谱
                aiService.generateGraphDataStream(graphRequest.getMessage(), handler);
                
            } catch (Exception e) {
                System.err.println("处理知识图谱生成请求时出错: " + e.getMessage());
                e.printStackTrace();
                
                try {
                    JsonObject errorEvent = new JsonObject();
                    errorEvent.addProperty("name", "error");
                    errorEvent.addProperty("data", "生成知识图谱时出错: " + e.getMessage());
                    
                    emitter.send(SseEmitter.event()
                        .name("message")
                        .data(errorEvent.toString()));
                    
                    emitter.completeWithError(e);
                } catch (IOException ex) {
                    System.err.println("发送错误消息失败: " + ex.getMessage());
                    emitter.completeWithError(e);
                }
            }
        });
        
        return emitter;
    }
} 
